<template>
  <div class="m-staff-base-info">
    <div class="m-h3-btn-box border">
      <h3>基本信息</h3>
      <div class="u-btn-box">
        <el-button type="primary" @click="baseInformationSave()" size="small">
          {{ isBaseInformationSave ? '保存' : '编辑' }}</el-button
        >
      </div>
    </div>
    <el-form
      :model="detail"
      label-width="100px"
      label-position="right"
      :rules="baseRules"
      class="form"
      ref="baseInformation"
    >
      <el-row :gutter="40">
        <el-col :span="8">
          <el-form-item label="" prop="head_url">
            <el-upload
              class="avatar-uploader"
              :action="url"
              :show-file-list="false"
              :disabled="!isBaseInformationSave"
              :http-request="uploadBaseInformationImg"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="detail.head_url"
                :src="detail.head_url"
                class="avatar"
              />
              <span
                class="el-upload-list__item-delete"
                @click.stop="handleRemove()"
                v-if="detail.head_url"
                >x</span
              >
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-row :gutter="40">
            <el-col :span="11">
              <el-form-item label="姓名：" prop="real_name">
                <el-input
                  v-model="detail.real_name"
                  placeholder="请输入姓名"
                  clearable
                  :disabled="!isBaseInformationSave"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="昵称：" prop="nick_name">
                <el-input
                  v-model="detail.nick_name"
                  placeholder="请输入昵称"
                  clearable
                  :disabled="!isBaseInformationSave"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="40">
            <el-col :span="11">
              <el-form-item label="性别：" prop="sex">
                <el-select
                  v-model="detail.sex"
                  placeholder="请选择性别"
                  :disabled="!isBaseInformationSave"
                >
                  <el-option label="男" :value="0"></el-option>
                  <el-option label="女" :value="1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="生日：" prop="birth_date">
                <el-date-picker
                  v-model="detail.birth_date"
                  type="date"
                  value-format="yyyy-MM-dd"
                  format="yyyy-MM-dd"
                  :picker-options="pickerOptions"
                  placeholder="请选择生日"
                  class="date-picker"
                  :disabled="!isBaseInformationSave"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="40">
            <el-col :span="11">
              <el-form-item label="年龄：" prop="age">
                <el-input
                  v-model="detail.age"
                  placeholder="请输入年龄"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="家庭住址：" prop="address">
                <el-input
                  v-model="detail.address"
                  placeholder="请输入家庭住址"
                  :disabled="!isBaseInformationSave"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="40">
            <el-col :span="11">
              <el-form-item label="毕业院校：" prop="graduate_school">
                <el-input
                  v-model="detail.graduate_school"
                  placeholder="请输入毕业院校"
                  :disabled="!isBaseInformationSave"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="学历：" prop="education">
                <el-input
                  v-model="detail.education"
                  placeholder="请输入学历"
                  :disabled="!isBaseInformationSave"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="40">
            <el-col :span="11">
              <el-form-item label="联系方式：" prop="mobile">
                <el-input
                  v-model="detail.mobile"
                  placeholder="请输入联系方式"
                  :disabled="!isBaseInformationSave"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="邮箱：" prop="email">
                <el-input
                  v-model="detail.email"
                  placeholder="请输入邮箱"
                  :disabled="!isBaseInformationSave"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="40">
            <el-col :span="11">
              <el-form-item label="所属部门：" prop="department_id">
                <el-cascader
                  :options="departmentList"
                  v-model="detail.department_id"
                  placeholder="请选择所属部门"
                  :show-all-levels="false"
                  :disabled="!isBaseInformationSave"
                  :props="{ checkStrictly: true }"
                  clearable
                ></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="岗位：" prop="position_id">
                <el-cascader
                  :options="positionList"
                  v-model="detail.position_id"
                  :props="{ checkStrictly: true }"
                  :show-all-levels="false"
                  :disabled="!isBaseInformationSave"
                  placeholder="请选择岗位"
                  clearable
                ></el-cascader>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="40">
            <el-col :span="11" class="margin-left20">
              <b>账号：{{ detail.username }}</b>
            </el-col>
            <el-col :span="11" class="margin-left20">
              <b>状态：{{ $filterEnums(detail.status, statusList) }}</b>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>
<script>
import { ossUpload, tableUpdate } from '@/api/api.js'
export default {
  props: {
    staffId: '',
    url: {
      type: String,
      default: ''
    },
    departmentList: {
      type: Array,
      default: function () {
        return []
      }
    },
    positionList: {
      type: Array,
      default: function () {
        return []
      }
    },
    selectEnums: {
      type: Object,
      default: function () {
        return {}
      }
    },
    baseInfo: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  data () {
    const validateMobile = (rule, value, callback) => {
      if (!this.$valid.isMobile(value)) {
        callback(new Error('手机号格式错误'))
      } else {
        callback()
      }
    }
    const validateEmail = (rule, value, callback) => {
      if (value !== '') {
        if (!this.$valid.isEmail(value)) {
          callback(new Error('邮箱格式错误'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      detail: {
        head_url: '',
        real_name: '',
        nick_name: '',
        sex: '',
        birth_date: '',
        age: '',
        address: '',
        graduate_school: '',
        education: '',
        mobile: '',
        email: '',
        department_id: '',
        position_id: '',
        username: '',
        status: ''
      },
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      },
      statusList: [
        { label: '在职', value: 0 },
        { label: '离职', value: 1 }
      ],
      isBaseInformationSave: false,
      baseRules: {
        real_name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        nick_name: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
        birth_date: [
          { required: true, message: '请选择生日', trigger: 'change' }
        ],
        graduate_school: [
          { required: true, message: '请输入毕业院校', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入联系方式', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }
        ],
        email: [{ required: false, validator: validateEmail, trigger: 'blur' }]
      }
    }
  },
  watch: {
    baseInfo: {
      handler (val) {
        if (val) {
          this.isBaseInformationSave = false
          this.detail.head_url = val.head_url || ''
          this.detail.real_name = val.real_name || ''
          this.detail.nick_name = val.nick_name || ''
          this.detail.sex = val.sex === 2 ? '' : val.sex
          this.detail.birth_date = val.birth_date || ''
          this.detail.address = val.address || ''
          this.detail.graduate_school = val.graduate_school || ''
          this.detail.education = val.education || ''
          this.detail.mobile = val.mobile || ''
          this.detail.email = val.email || ''
          this.detail.department_id =
            this.$familyTree(val.department_id, this.departmentList) || []
          this.detail.position_id =
            this.$familyTree(val.position_id, this.positionList) || []
          this.detail.username = val.username || ''
          this.detail.status = val.status
          this.$nextTick(() => {
            this.$refs['baseInformation'].clearValidate()
          })
        }
      },
      deep: true,
      immediate: true
    },
    'detail.birth_date' (val, oldval) {
      this.detail.age = this.detail.birth_date
        ? this.$age(this.$formatDate(val, 'yyyy-MM-dd'))
        : ''
    }
  },
  methods: {
    baseInformationSave () {
      if (this.isBaseInformationSave) {
        this.$refs['baseInformation'].validate(valid => {
          if (valid) {
            this.submit()
          }
        })
      } else {
        this.isBaseInformationSave = true
      }
    },
    async submit () {
      let res = await tableUpdate([
        {
          table_name: 'nice_user_base',
          update: [
            {
              real_name: this.detail.real_name,
              nick_name: this.detail.nick_name,
              sex: this.detail.sex,
              birth_date: this.detail.birth_date,
              mobile: this.detail.mobile,
              address: this.detail.address,
              head_url: this.detail.head_url,
              email: this.detail.email,
              inner: [
                {
                  graduate_school: this.detail.graduate_school,
                  education: this.detail.education,
                  department_id:
                    this.detail.department_id &&
                    this.detail.department_id.length
                      ? this.detail.department_id[
                          this.detail.department_id.length - 1
                        ]
                      : '',
                  position_id:
                    this.detail.position_id && this.detail.position_id.length
                      ? this.detail.position_id[
                          this.detail.position_id.length - 1
                        ]
                      : '',
                  status: this.detail.status
                }
              ]
            }
          ],
          where: [
            {
              sys_user_id: this.staffId
            }
          ]
        }
      ])
      if (res[0]) {
        return
      }
      let data = res[1]
      if (data && data.code === 0) {
        this.$message.success('保存成功！')
        this.isBaseInformationSave = false
        this.$emit('refreshData')
      } else {
        this.$message.error(res[1].msg)
      }
    },
    async uploadBaseInformationImg (e) {
      let formData = new FormData()
      formData.append('file', e.file)
      let res = await ossUpload(formData, 'STAFF_PORTRAIT')
      if (res[0]) {
        return
      }
      this.detail.head_url = res[1].data.url
    },
    beforeAvatarUpload (file) {
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传的封面图片只能是 JPG 或 PNG 格式或 GIF 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传的封面图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleRemove () {
      this.detail.head_url = ''
    }
  }
}
</script>
<style lang="scss" scoped></style>
